package yunc.checkData.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class IOutil {
    private static Logger logger = LoggerFactory.getLogger(IOutil.class.getName());

    public static void write(String filePath, List<String> strList){
        write(filePath,strList,true);
    }

    public static void write(String filePath, List<String> strList, boolean appended){

        try {
            BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(filePath,appended),"UTF-8"));
            for (int i = 0; i < strList.size(); i++) {
                writer.write(strList.get(i));
                writer.write("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("向文件： "+filePath+" 中写入数据完成");
    }



    public static List<String> read(String filePath){
        List<String> strings = new ArrayList<>();
        try {
            Path path = Paths.get(filePath);
            File file = new File(path.toString());
         //   String fileCharset = new CpdetectorUtils().getFileOrIOEncode(path.toString(),"file");
//            strings = Files.readAllLines(path, Charset.forName("UTF-8"));
            logger.info("文件" + filePath + "的文件编码是: " + "utf-8");
            strings = Files.readAllLines(path, Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return repleceStrBOM(strings);
    }

    public static List<String> repleceStrBOM(List<String> strs){
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < strs.size(); i++) {
            String str="";
            if (strs.get(i).charAt(0) == '\uFEFF'){
                logger.info("字符串" + strs.get(i) + "包含BOM字符'\\uFEFF',将会去掉这个字符");
                str=strs.get(i).substring(1);
            }else {
                str=strs.get(i);
            }
            strings.add(i,str);
        }
        return strings;
    }

}
